package org.hhgzs.modules.erp.controller;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hhgzs.modules.erp.entity.Material;
import org.hhgzs.modules.erp.entity.MaterialProperty;
import org.hhgzs.modules.erp.vo.MaterialVo;
import org.hhgzs.modules.erp.vo.MaterialVo4Unit;
import org.hhgzs.modules.erp.service.MaterialService;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 产品表 前端控制器
 * </p>
 *
 * @author peiqy
 * @since 2021-07-14
 */
@RestController
@RequestMapping("/material")
@Slf4j
@RequiredArgsConstructor
@Api("结算账户管理")
public class MaterialController extends JeecgController<Material, MaterialService> {

    private final MaterialService materialService;


    @GetMapping(value = "/checkIsExist")
    public Result checkIsExist(@RequestParam("id") Long id, @RequestParam("name") String name,
                               @RequestParam("model") String model, @RequestParam("color") String color,
                               @RequestParam("standard") String standard, @RequestParam("mfrs") String mfrs,
                               @RequestParam("otherField1") String otherField1, @RequestParam("otherField2") String otherField2,
                               @RequestParam("otherField3") String otherField3, @RequestParam("unit") String unit,@RequestParam("unitId") Long unitId,
                               HttpServletRequest request)throws Exception {
        Map<String, Object> objectMap = new HashMap<String, Object>();

        int exist = materialService.checkIsExist(id, name, StrUtil.blankToDefault(model,null), StrUtil.blankToDefault(color,null),
                StrUtil.blankToDefault(standard,null), StrUtil.blankToDefault(mfrs,null), StrUtil.blankToDefault(otherField1,null),
                StrUtil.blankToDefault(otherField2,null), StrUtil.blankToDefault(otherField3,null), StrUtil.blankToDefault(unit,null), unitId);
        if(exist > 0) {
            objectMap.put("status", true);
        } else {
            objectMap.put("status", false);
        }
        return Result.OK(objectMap);
    }


    /**
     * update
     *
     */
    @RequestMapping("/updateX")
    public Result updateX(@RequestBody MaterialVo data) {
        boolean b = materialService.update(data);
        if(b){
            return Result.OK(true);
        }else{
            return Result.OK(false);
        }
    }

    /**
     * update
     *
     */
    @RequestMapping("/addX")
    public Result saveX(@RequestBody MaterialVo data) {
        boolean b = materialService.save(data);
        if(b){
            return Result.OK(true);
        }else{
            return Result.OK(false);
        }
    }

    /**
     * 获取用户列表数据
     *
     * @param data
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @PermissionData(pageComponent = "basedata/DepotList")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiOperation("列表查询")
    public Result<IPage<Material>> queryPageList(Material data, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        Result<IPage<Material>> result = new Result<IPage<Material>>();
        QueryWrapper<Material> queryWrapper = QueryGenerator.initQueryWrapper(data, req.getParameterMap());

        Page<Material> page = new Page<Material>(pageNo, pageSize);
        IPage<Material> pageList = materialService.page(page, queryWrapper);

        result.setSuccess(true);
        result.setResult(pageList);
        log.info(pageList.toString());
        return result;
    }

    /**
     * update
     *
     */
    @DeleteMapping("/delete")
    @ApiOperation("删除")
    public Result<?> delete(@RequestParam(required = true) Serializable id) {
        boolean b = materialService.removeById(id);
        if(b){
            return Result.OK().success("删除成功!");
        }else{
            return Result.OK(false);
        }
    }

    @GetMapping(value = "/getMaterialEnableSerialNumberList")
    public Result<IPage<MaterialVo4Unit>> getMaterialEnableSerialNumberList(
            @RequestParam(value = "q", required = false) String q,
            @RequestParam("page") Integer pageNo,
            @RequestParam("rows") Integer pageSize,
            HttpServletRequest request,
            HttpServletResponse response)throws Exception {
            Result<IPage<MaterialVo4Unit>> result = new Result<IPage<MaterialVo4Unit>>();
            Page<MaterialVo4Unit> page = new Page<MaterialVo4Unit>(pageNo, pageSize);
            IPage<MaterialVo4Unit> pageList = materialService.getMaterialEnableSerialNumberList(page,q);
            Long count = materialService.getMaterialEnableSerialNumberCount(q);
            result.setSuccess(true);
            result.setResult(pageList);
            log.info(pageList.toString());
            return result;
    }

    /**
     * 根据条码查询商品信息
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/getMaterialByBarCode")
    public Result getMaterialByBarCode(@RequestParam("barCode") String barCode,
                                                 @RequestParam("mpList") String mpList,
                                                 @RequestParam(required = false, value = "prefixNo") String prefixNo,
                                                 HttpServletRequest request) throws Exception {
        try {
            String[] mpArr = mpList.split(",");
            MaterialVo4Unit mu = new MaterialVo4Unit();
            List<MaterialVo4Unit> list = materialService.getMaterialByBarCode(barCode);
            if(list!=null && list.size()>0) {
                mu = list.get(0);
                String expand = ""; //扩展信息
                for (int i = 0; i < mpArr.length; i++) {
                    if (mpArr[i].equals("制造商")) {
                        expand = expand + ((mu.getMfrs() == null || mu.getMfrs().equals("")) ? "" : "(" + mu.getMfrs() + ")");
                    }
                    if (mpArr[i].equals("自定义1")) {
                        expand = expand + ((mu.getOtherField1() == null || mu.getOtherField1().equals("")) ? "" : "(" + mu.getOtherField1() + ")");
                    }
                    if (mpArr[i].equals("自定义2")) {
                        expand = expand + ((mu.getOtherField2() == null || mu.getOtherField2().equals("")) ? "" : "(" + mu.getOtherField2() + ")");
                    }
                    if (mpArr[i].equals("自定义3")) {
                        expand = expand + ((mu.getOtherField3() == null || mu.getOtherField3().equals("")) ? "" : "(" + mu.getOtherField3() + ")");
                    }
                }
                mu.setMaterialOther(expand);
                if("LSCK".equals(prefixNo) || "LSTH".equals(prefixNo)) {
                    //零售价
                    mu.setBillPrice(mu.getCommodityDecimal());
                } else if("CGDD".equals(prefixNo) || "CGRK".equals(prefixNo) || "CGTH".equals(prefixNo)
                        || "QTRK".equals(prefixNo) || "DBCK".equals(prefixNo) || "ZZD".equals(prefixNo) || "CXD".equals(prefixNo) ) {
                    //采购价
                    mu.setBillPrice(mu.getPurchaseDecimal());
                } else if("XSDD".equals(prefixNo) || "XSCK".equals(prefixNo) || "XSTH".equals(prefixNo) || "QTCK".equals(prefixNo)) {
                    //销售价
                    mu.setBillPrice(mu.getWholesaleDecimal());
                }
            }
            return Result.OK(mu);
        } catch(Exception e){
            e.printStackTrace();
            return Result.error("获取数据失败");
        }
    }
}
